package com.chint.springboot.config;

import com.chint.springboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        // 获取请求的URI
        String requestURI = request.getRequestURI();

        // 检查请求路径是否为 /login/in，如果是则直接放行
        if ("/login/in".equals(requestURI) || "/login".equals(requestURI) || "/home".equals(requestURI)) {
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader("Authorization");
        String  jwt = token.substring(7);
        if (token != null && !token.isEmpty()) {
            JwtUtils tokenUtil = new JwtUtils();
            Claims claims = tokenUtil.getClaimsByToken(jwt);
            if (claims != null) {
                return true;
            }
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Unauthorized");
        return false;


    }
}
